import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import tailwindcss from '@tailwindcss/vite'
import copyDist from './src/plugins/vite-plugin-copy'

const TARGET_DIR = '../ainode/dist'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    tailwindcss(),
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    copyDist(TARGET_DIR)
  ],
  server: {
    proxy: {
      '/api': {
        target: 'https://spark-api-open.xf-yun.com', // 目标服务器地址
        changeOrigin: true, // 是否改变源地址
        rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径
      }
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler' // or "modern", "legacy"
      },
    },
  },
  // ******项目构建配置******
  // build: {
  //   target: 'modules', //设置最终构建的浏览器兼容目标  //es2015(编译成es5) | modules
  //   outDir: 'dist', // 构建得包名  默认：dist
  //   assetsDir: 'assets', // 静态资源得存放路径文件名  assets
  //   sourcemap: false, //构建后是否生成 source map 文件
  //   minify: 'esbuild', // 项目压缩 :boolean | 'terser' | 'esbuild'
  //   chunkSizeWarningLimit: 1000, //chunk 大小警告的限制（以 kbs 为单位）默认：500
  //   cssTarget: 'chrome61' //防止 vite 将 rgba() 颜色转化为 #RGBA 十六进制符号的形式  (要兼容的场景是安卓微信中的 webview 时,它不支持 CSS 中的 #RGBA 十六进制颜色符号)
  // },
  build: {
    rollupOptions: {
      output: {
        // Organize js files
        entryFileNames: 'js/[name]-[hash].js',
        chunkFileNames: 'js/[name]-[hash].js',
        assetFileNames: (assetInfo: any) => {
          const info = assetInfo.name.split('.')
          const extType = info[info.length - 1]
          
          // Organize by file type
          if (/\.(css|scss|sass|less|styl)$/.test(assetInfo.name)) {
            return `css/[name]-[hash].${extType}`
          }
          if (/\.(png|jpe?g|gif|svg|webp|ico)$/.test(assetInfo.name)) {
            return `images/[name]-[hash].${extType}`
          }
          
          // Default case for other assets
          return `assets/[name]-[hash].${extType}`
        },
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
        }
        // chunkFileNames: (chunkInfo) => {
        //   const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : [];
        //   const fileName = facadeModuleId[facadeModuleId.length - 2] || '[name]';
        //   return `js/${fileName}/[name].[hash].js`;
        // }
      },
    },
  },
  resolve: {
    alias: {
      // 别名配置
      // 键必须以斜线开始和结束
      '@': resolve(__dirname, './src'),
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  }
})
